<template>
  <el-card shadow="never">
    <template #header>
      <div class="my--1.5 flex flex-row items-center justify-between">
        <CardTitle title="项目统计" />
      </div>
    </template>
    <div class="min-w-225 py-1.75" v-loading="loading">
      <div ref="chartRef" class="chart-container"></div>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { CardTitle } from '@/components/Card';
import { onMounted, ref, onBeforeUnmount, nextTick } from "vue";
import * as echarts from "echarts";
import { StatisticsApi } from "@/api/project/statistics";

/** 项目统计卡片 */
defineOptions({ name: 'ProjectBarChart' });

const loading = ref(true); // 加载状态
const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

// 图表选项
const chartOptions: echarts.EChartsOption = {
  tooltip: {
    trigger: "axis",
    axisPointer: { type: "shadow" },
  },
  legend: {
    data: [], // 动态设置
  },
  toolbox: {
    show: true,
    orient: "vertical",
    left: "right",
    top: "center",
    feature: {
      mark: { show: true },
      dataView: { show: true, readOnly: false },
      magicType: { show: true, type: ["line", "bar", "stack"] },
      restore: { show: true },
      saveAsImage: { show: true },
    },
  },
  xAxis: [
    {
      type: "category",
      axisTick: { show: false },
      data: [], // 动态设置
    },
  ],
  yAxis: [{ type: "value" }],
  series: [], // 动态设置
};

const getProjectBarEcharts = async () => {
  loading.value = true;
  const res = await StatisticsApi.getProjectBarEcharts();

  // X轴数据
  const xAxisData = res.map(item => item.projectName);

  // 图例数据
  const legendData = ["批次数量", "打分次数"];

  // Series 数据
  const seriesData = [
    {
      name: "批次数量",
      type: "bar",
      data: res.map(item => item.assessmentBatchCount),
    },
    {
      name: "打分次数",
      type: "bar",
      data: res.map(item => item.checkRecordCount),
    },
  ];

  // 更新图表选项
  chartOptions.xAxis[0].data = xAxisData;
  chartOptions.legend.data = legendData;
  chartOptions.series = seriesData;

  // 更新图表
  if (chartInstance) {
    chartInstance.setOption(chartOptions);
  }
  loading.value = false;
};

// 初始化图表
const initChart = async () => {
  await nextTick(); // 确保 DOM 已渲染
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    await getProjectBarEcharts(); // 加载数据并更新图表
  }
};

// 生命周期钩子
onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  chartInstance?.dispose();
});
</script>

<style lang="scss" scoped>
.chart-container {
  width: 100%;
  height: 400px;
}
</style>
